package cn.android.support.v7.lib.sin.crown.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

import cn.android.support.v7.lib.sin.crown.utils.ProportionUtils;

/**
 * 按顺序显示位图图片。
 * Created by 彭治铭 on 2018/1/18.
 */

public class BitmapArrayView extends View {
    public BitmapArrayView(Context context) {
        super(context);
        init();
    }

    public BitmapArrayView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    Paint paint;

    private void init() {
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setDither(true);
    }

    List<Bitmap> bitmaps = new ArrayList<>();//位图数组。最多最好为3张。

    public List<Bitmap> getBitmaps() {
        return bitmaps;
    }

    public void setBitmaps(List<Bitmap> bitmaps, int mWidth) {
        if (this.bitmaps.size() > 0) {
            for (int i = 0; i < this.bitmaps.size(); i++) {
                this.bitmaps.get(i).recycle();
            }
            this.bitmaps.clear();
        }
        if (bitmaps != null && bitmaps.size() > 0) {
            this.mWidth = mWidth;
            this.mHeight = mWidth + offset;
            this.bitmaps = bitmaps;
            requestLayout();
        }
    }

    int mWidth = 0, mHeight = 0;//位图的宽度和高度。
    int offset = ProportionUtils.getInstance().adapterInt(12);//图片与图片之间的间隙。

    public int getmWidth() {
        return mWidth;
    }

    public void setmWidth(int mWidth) {
        this.mWidth = mWidth;
    }

    public int getmHeight() {
        return mHeight;
    }

    public void setmHeight(int mHeight) {
        this.mHeight = mHeight;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (bitmaps != null && bitmaps.size() > 0) {
            setMeasuredDimension((mWidth + offset) * bitmaps.size(), mHeight);
        } else {
            super.onMeasure(widthMeasureSpec, 0);
        }

    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        if (bitmaps != null && bitmaps.size() > 0) {
            int x = 0;
            int y = 0;
            for (int i = 0; i < bitmaps.size(); i++) {
                Bitmap bitmap = bitmaps.get(i);
                x = (mWidth + offset) * i;
                canvas.drawBitmap(bitmap, x, y, paint);
            }
        }
    }
}
